package com.kchouse.union;


import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.StartActivity;
import com.kchouse.bean.MerchantItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseFragment;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;


/**
 * A simple {@link Fragment} subclass.
 */
public class GDMapFragment extends BaseFragment implements LocationSource {


    private View view;
    private FragmentActivity mContext;
    private MapView mMapView;
    private AMap aMap;
    private AMapLocationClient aMapLocationClient;
    private AMapLocationClientOption aMapLocationClientOption;
    private LocationSource.OnLocationChangedListener listener;
    private ArrayList<MerchantItem> listmerchant = new ArrayList<>();

    public GDMapFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        if (view == null) {
            view = inflater.inflate(R.layout.fragment_gdmap, null);
            mContext = getActivity();
            intiData();
            intiView();
            mMapView.onCreate(savedInstanceState);
        } else {
            if (view.getParent() != null) {
                ((ViewGroup) view.getParent()).removeView(view);
            }
        }

        return view;
    }

    private void intiData() {

        GetMerchantList();
    }


    private void intiView() {
        //获取地图控件引用
        mMapView = (MapView) view.findViewById(R.id.map);

        intiMap();
    }

    /**
     * 获取商家列表
     */
    private void GetMerchantList() {
        String url = API.GetMerchantList;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {


            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    listmerchant.clear();
                    listmerchant.addAll(JSONObject.parseArray(data.getString("merchantList"), MerchantItem.class));

                    for (int i = 0; i < listmerchant.size(); i++) {
                        MerchantItem item = listmerchant.get(i);
                        addMarker(item.getLatitude(), item.getLongitude(), item.getName(), item.getAddress());
                    }

                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(getActivity()).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    /**
     * 添加地图的标记
     */
    private void addMarker(String latitudestr, String longitudestr, String title, String snippet) {
        Double latitude = Double.valueOf(latitudestr);
        Double longitude = Double.valueOf(longitudestr);
        LatLng latLng = new LatLng(latitude, longitude);
        MarkerOptions markerOptions = new MarkerOptions().position(latLng)
                .title(title)
                .snippet(snippet)
                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_marker))
                .draggable(false)
                .visible(true)
                .anchor(0.5f, 1f);
        aMap.addMarker(markerOptions);

        // 点击事件
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
//                Log.e("TAG", "onMarkerClick:" + marker.getTitle());

//                ToastUtils.getInstanc(mContext).showToast("Title:"
//                        + marker.getTitle() + ", 描述:"
//                        + marker.getSnippet()+"经度："
//                        +marker.getPosition().longitude+"维度："
//                        +marker.getPosition().latitude);

                marker.showInfoWindow();
                return false;
            }
        });

    }


    /**
     * 初始化高德地图
     */
    private void intiMap() {

        aMap = mMapView.getMap();
        //设置地图类型
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(13));//最大15

        MyLocationStyle locationStyle = new MyLocationStyle();
        locationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_mylog));

        locationStyle.strokeColor(Color.BLUE);
        locationStyle.strokeWidth(5);
        aMap.setMyLocationStyle(locationStyle);

        // 设置定位监听
        aMap.setLocationSource(this);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式，参见类AMap。
        aMap.setMyLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
        // 设置为true表示系统定位按钮显示并响应点击，false表示隐藏，默认是false
        aMap.setMyLocationEnabled(true);

        if (listener != null && StartActivity.maMapLocation != null) {
            listener.onLocationChanged(StartActivity.maMapLocation);// 显示系统小蓝点
        }
    }

    @Override
    public void activate(LocationSource.OnLocationChangedListener onLocationChangedListener) {
        listener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {

    }


    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onDestroy() {
        Log.i("sys", "mf onDestroy");
        super.onDestroy();
        mMapView.onDestroy();
    }


    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

}
